<template>
  <section class="chart-container">
    <div class="c_header systemManage">
      <div class="content">
        <div class="main-content">
          <div>
            <!-- 机构首页 -->
            <div class="cont">
              <span class="text" style="font-size:14px;float:left">上级机构：{{this.suplist.orgname}}</span>
              <div class="btn-group" style="float:right">
                <el-button size="mini" type="primary" @click="addJigouClick">增加同级机构</el-button>
                <el-button size="mini" type="primary" @click="getFirstJigouList()" v-if="this.suplist.suporgid!=''">向上</el-button>
                <!-- <span class="btn" @click="addJigouClick">增加同级机构</span>
                <span class="btn" @click="getFirstJigouList()" v-if="this.suplist.suporgid!=''">向上</span> -->

              </div>
              <table width="100%">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>名称</th>
                    <!-- <th>备注</th> -->
                    <th width="320px">操作</th>
                  </tr>
                </thead>
                <tbody style="background:#fff">
                  <tr v-for="item in jigouFirstList" :key="item.id">
                    <td>{{item.hash.orgid}}</td>
                    <td>{{item.hash.orgname}}</td>
                    <!-- <td>备注内容</td> -->
                    <td>
                      <span @click="getFirstJigouList(item.hash.orgid)">查看下级机构</span>
                      <span @click="equipmentapproved(item.hash.orgid)">设备批准人</span>
                      <span @click="modifyFirstJigouInfo(item.hash.orgid)">修改</span>
                      <el-button size="mini" type="text" @click="deleteAreaItem(item.hash.orgid)">删除</el-button>
                    </td>
                  </tr>
                  <tr>
                    <td v-if="jigouFirstList.length==0" colspan="4">暂无数据</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <!-- 增加机构 -->
            <el-dialog title="机构管理" :visible.sync="dialogTableVisible7">
              <div class="addInfo">
                <div class="title">{{orgtitle}}</div>
                <table width="95%">
                  <tbody>
                    <tr>
                      <td>上级机构:</td>
                      <td><input type="text" :value="this.suplist.orgname+'--'+this.suplist.orgid" readOnly></td>
                    </tr>
                    <tr>
                      <td>机构名称:</td>
                      <td><input type="text" v-model="newFirstJigou"></td>
                    </tr>
                    <tr v-if="orgtitle=='新增机构'">
                      <td>机构ID:</td>
                      <td><input type="text" v-model="newFirstJigouid"></td>
                    </tr>
                    <tr>
                      <td colspan="2" v-show="showFirstJigouSubmit" @click="addJigou"><span>提交</span></td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </el-dialog>
            <el-dialog title="设备批准人" :visible.sync="dialogTableVisible" width="20%" v-if="showtask">
              <el-form labelWidth="80px">
                <el-form-item label="批准人">
                  <el-select v-model="approved" placeholder="请选择" multiple collapseTags
                    @visible-change="visibleChange"
                  >
                    <el-option :value="mineStatusValue" style="height: auto">
                      <el-tree
                        :data="arr"
                        showCheckbox
                        checkStrictly
                        nodeKey="id"
                        ref="tree"
                        highlightCurrent
                        :props="defaultProps"
                        @check-change="handleCheckChange"
                        @node-click="nodeClick"
                      ></el-tree>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div class="foot">
                <el-button type="primary" size="mini" @click="approvedsave">保存</el-button>
                <el-button size="mini" @click="approvedcancel">取消</el-button>
              </div>
            </el-dialog>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>
<script>
export default {
  data() {
    return {
      dialogTableVisible: false,
      dialogTableVisible7: false,
      orgtitle: '新增机构',
      showFirstJigouSubmit: false,
      sideMenu: [],
      isRouterAlive: true,

      ts: this.newStore(),
      // 分页相关
      group: 1, // 分组
      total: 0, // 数据总数
      num: 1, // 当前页
      limit: '30', // 每组有多少条数据

      // 机构管理相关
      jigouFirstList: [], //
      suplist: {},
      nowOrgname: '', // 点击查看下级代码，保存当前一级结构的名称
      nowOrgid: '',
      nowSupid: '',
      newFirstJigou: '',
      newFirstJigouid: '',
      len: 0,
      arr: [],
      approved: '',
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      mineStatusValue: [],
      orgid: '',
      editCheckId: '',
      showtask: false,
    };
  },
  created() {
    // this.getSidemenu();
    this.getFirstJigouList('syslead');
    this.getTree();
  },

  methods: {
    getSidemenu() {
      const req = {
        handle: '67A5B6FEF17D97DECF116BDF95B95C0B078C37EB4CBA2359',
        token: localStorage.getItem('token'),
        supid: '200300',
      };
      this.spost(this.ts, '/mainservlet', req).then((ts) => {
        this.sideMenu = ts.d.data.operation1;
      });
    },
    reload(partsname) {
      this[partsname] = false;
      this.$nextTick(() => {
        this[partsname] = true;
      });
    },

    // 机构管理
    // 获取一级机构列表数据
    getFirstJigouList(supid) {
      if (!supid) {
        supid = this.suplist.suporgid;
      }
      const req = {
        handle: '67A5B6FEF17D97DECF116BDF95B95C0BC327730680009A98',
        token: localStorage.getItem('token'),
        suporgid: supid,
      };

      this.spost(this.ts, '/mainservlet', req).then((ts) => {
        this.suplist = ts.d.data.operation2[0].hash;
        console.log(' this.suplist', this.suplist);

        this.jigouFirstList = ts.d.data.operation1;
        if (!this.jigouFirstList[0].hash.orgid) {
          this.jigouFirstList = [];
        }
      });
    },

    // 增加一级机构
    addJigou() {
      let res;
      if (this.nowOrgid) {
        res = {
          handle: '67A5B6FEF17D97DE0AB0D17168BEEBCD04453EE0A5CF10A0',
          token: localStorage.getItem('token'),
          suporgid: this.nowSupid,
          orgname: this.newFirstJigou,
          remark: '',
          orgid: this.nowOrgid,

        };
      } else {
        res = {
          handle: '67A5B6FEF17D97DE8AD68148755261CACC426B34C0BBA8ED',
          token: localStorage.getItem('token'),
          suporgid: this.suplist.orgid,
          orgname: this.newFirstJigou,
          orgid: this.newFirstJigouid,
          remark: '',
        };
      }
      if (res.orgname == '') {
        this.$message({
          type: 'error',
          message: '请填写机构构名称',
        });
        return;
      }
      if (res.orgid == '') {
        this.$message({
          type: 'error',
          message: '请填写机构ID',
        });
        return;
      }
      this.spost(this.ts, '/mainservlet', res).then(() => {
        this.getFirstJigouList(this.suplist.orgid);
      });
      this.dialogTableVisible7 = false;
      this.showFirstJigouSubmit = false;
    },
    // 删除一级机构
    deleteAreaItem(orgid) {
      this.$confirm('确认删除?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const res = {
          handle: '67A5B6FEF17D97DEF1D0D23DA4270B6399C94A60607326CA',
          token: localStorage.getItem('token'),
          orgid,
          suporgid: this.suplist.orgid,
        };
        this.spost(this.ts, '/mainservlet', res).then((ts) => {
          if (ts.d.data.operation1[0].hash.msg == 'success') {
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
            this.getFirstJigouList();
          } else {
            this.$message({
              type: 'error',
              message: ts.d.data.operation1[0].hash.msg,
            });
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        });
      });
    },
    // 一级机构点击修改
    modifyFirstJigouInfo(orgid) {
      this.orgtitle = '修改机构';
      // 渲染单条信息
      const req = {
        handle: '67A5B6FEF17D97DE41472B87C055439393B923BD4A7449EE',
        token: localStorage.getItem('token'),
        orgid,
      };
      this.spost(this.ts, '/mainservlet', req).then((ts) => {
        this.nowOrgid = orgid;
        this.newFirstJigou = ts.d.data.operation1[0].hash.orgname;
        this.nowSupid = ts.d.data.operation1[0].hash.suporgid;
      });

      this.showFirstJigouSubmit = true;
      this.dialogTableVisible7 = true;
    },


    // 到新增机构页
    addJigouClick() {
      this.orgtitle = '新增机构';
      this.nowOrgid = '';
      this.showFirstJigouSubmit = true;
      this.newFirstJigou = '';
      this.newFirstJigouid = '';
      this.dialogTableVisible7 = true;
    },
    equipmentapproved(id) {
      this.approved = [];
      this.showtask = false;
      this.reload('showtask');
      const req = {
        handle:
          '67A5B6FEF17D97DE41472B87C055439393B923BD4A7449EE',
        orgid: id,
      };
      this.spost(this.ts, '/mainservlet', req).then((ts) => {
        if (ts.d.sflag == 'success') {
          this.dialogTableVisible = true;
          this.approved = [];
          this.approved.push(ts.d.data.operation2[0].hash.username);
          this.editCheckId = ts.d.data.operation2[0].hash.pzrid;
          this.mineStatusValue = [];
          this.mineStatusValue.push({ id: ts.d.data.operation2[0].hash.pzrid, label: ts.d.data.operation2[0].hash.username });
        }
      });

      this.orgid = id;
    },
    visibleChange() {
      this.$refs.tree.setCheckedNodes(this.mineStatusValue);
    },
    handleCheckChange(item, isChecked) {
      // const res = this.$refs.tree.getCheckedNodes(true, true); // 这里两个true，1. 是否只是叶子节点 2. 是否包含半选节点（就是使得选择的时候不包含父节点）
      // const arrLabel = [];
      // const arr = [];
      // const tt = [];
      // res.forEach((item) => {
      //   arrLabel.push(item.label);
      //   arr.push(item);
      //   tt.push(item.id);
      // });
      // // console.log(arr,'1')
      // // console.log(arrLabel,'2')
      // this.mineStatusValue = arr;
      // this.planperson = tt;
      // this.approved = arrLabel;
      // if (arr.length > 0) {
      //   this.flag = true;
      // } else {
      //   this.flag = false;
      // }
      if (isChecked == true) {
        this.editCheckId = item.id;
        this.approved = [];
        this.approved.push(item.label);
        this.$refs.tree.setCheckedKeys([item.id]);
        this.mineStatusValue = this.$refs.tree.getCheckedNodes(true, true);

        console.log(this.editCheckId, item, this.mineStatusValue);
      } else if (this.editCheckId == item.id) {
        this.$refs.tree.setCheckedKeys([item.id]);
        this.mineStatusValue = this.$refs.tree.getCheckedNodes(true, true);
        console.log(this.editCheckId, this.mineStatusValue);
      }
    },
    nodeClick(item) {
      this.editCheckId = item.id;
      this.$refs.tree.setCheckedKeys([item.id]);
    },
    getTree() {
      const req = {
        handle:
          '45EE8FEFE87870C53A0536D8566DA8C94345851CDDF60960CBCA139672EA5B8C230BE336D992C9E341DC33B3A5E90841',
      };
      this.spost(this.ts, '/mainservlet', req).then((ts) => {
        if (ts.d.sflag == 'success') {
          this.getTreedata(ts.d.data.operation1);
          console.log(ts.d.data.operation1, 'ts.d.data.operation1');
        }
      });
    },
    getTreedata(data) {
      const arr = data;
      const arr1 = arr.map(item => item.hash);
      const date = [];
      const obj = {
        id: 987654321,
        label: '全部',
        children: [],
      };
      arr1.forEach((item) => {
        if (!date.includes(item.orgname)) {
          date.push(item.orgname);
        }
      });
      const ars = [];
      date.forEach((item, ind) => {
        ars.push({
          id: ind,
          label: item,
          children: [],
        });
      });
      arr1.forEach((item) => {
        ars.forEach((file) => {
          if (file.label === item.orgname) {
            file.children.push({
              id: item.pid,
              label: item.username,
            });
          }
        });
      });
      obj.children = ars;
      this.arr.push(obj);
    },
    approvedsave() {
      this.$confirm('确认该任务已完成？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const req = {
          handle:
          '67A5B6FEF17D97DEE5FB3EC2509558B2E8BD78D2B41AC051F56ACA32054A5F21',
          orgid: this.orgid,
          pzrid: this.editCheckId,
        };
        this.spost(this.ts, '/mainservlet', req).then((ts) => {
          if (ts.d.sflag == 'success') {
            this.dialogTableVisible = false;
          }
        });
      });
    },
    approvedcancel() {
      this.dialogTableVisible = false;
    },
  },
};
</script>
<style scoped>
.foot{
  text-align: right;
}

</style>
